package com.example.demo.Service.lmp;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.Dto.CheckoutDto;
import com.example.demo.Mapper.CheckoutMapper;
import com.example.demo.Service.CheckoutService;
import com.example.demo.Service.OrderItemService;
import com.example.demo.Service.OrderService;
import com.example.demo.Util.RedisUtli;
import com.example.demo.Util.ThreadLocallUtil;
import com.example.demo.Util.ThreadPoolUtil;
import com.example.demo.VO.CheckoutVo;
import com.example.demo.po.Checkout;
import com.example.demo.po.Order;
import com.example.demo.po.OrderItem;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CheckoutServiceImp  extends ServiceImpl<CheckoutMapper, Checkout> implements CheckoutService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RedisUtli redisUtli;
    @Override
    @Transactional
    public CheckoutVo eddCheckout(CheckoutDto checkoutDto) {
        String s = orderService.addOrders(checkoutDto.getPlaceOrderDto());
        ThreadPoolUtil.execute(() -> {
            if (!(orderService.update(new UpdateWrapper<Order>().eq("order_id", s)
                    .set("status", 1)
                    .set("pay_time", new DateTime())
                    .set("update_time", new DateTime())))){
                throw new RuntimeException("订单:修改失败");
            }
            orderItemService.update(new UpdateWrapper<OrderItem>().eq("order_id", s).set("status", 1));
            redisTemplate.opsForValue().getAndDelete("订单"+ s);
        });
        Checkout build = Checkout.builder().userId(ThreadLocallUtil.getUser().getUserId())
                .cartId(checkoutDto.getCartId())
                .orderId(s)
                .status(0)
                .firstName(checkoutDto.getFirstName())
                .lastName(checkoutDto.getLastName())
                .build();
        if (!(save(build))){
            throw new RuntimeException("订单:保存失败");
        }
        CheckoutVo checkoutVo = new CheckoutVo();
        checkoutVo.setOrderId(s);
        checkoutVo.setTransactionId(redisUtli.generateId("transactionId").toString());
        return checkoutVo;
    }
}
